package com.paginasenlanube.controller;


import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;

import com.paginasenlanube.model.Image;
import com.paginasenlanube.model.Website;
import com.paginasenlanube.service.ImageService;

import com.paginasenlanube.utils.UserException;
import com.paginasenlanube.utils.Utils;

 
@Controller
@RequestMapping("/controller")
public class FileController {

	
	@Autowired
	 ImageService imageService;
	
	
	public ImageService getImageService() {
		return imageService;
	}
	
	@Autowired
	   private Website website;
	
	@Resource(name = "myProps")
    private Properties myProps;
 
    LinkedList<Image> files = new LinkedList<Image>();
    
    /***************************************************
     * URL: controller/upload  
     * upload(): receives files
     * @param request : MultipartHttpServletRequest auto passed
     * @param response : HttpServletResponse auto passed
     * @return LinkedList<Image> as json format
     ****************************************************/
    @RequestMapping(value="/upload", method = RequestMethod.POST)
    public @ResponseBody String upload(MultipartHttpServletRequest request, HttpServletResponse response) {
         
    	 files.clear();
        //1. build an iterator
         Iterator<String> itr =  request.getFileNames();
         String key = request.getParameter("key");
         String pageId = request.getParameter("pageId");
         MultipartFile mpf = null;
         Image image = null;
         String errorMsj="";
         Map<String, Integer> mp = Utils.getImageDimension(key,pageId,website,myProps);
 		 int width = (Integer) mp.get("width");
		 int height = (Integer) mp.get("height");
		 long websiteId = website.getId();
 
         //2. get each file
         while(itr.hasNext()){
 
             //2.1 get next MultipartFile
             mpf = request.getFile(itr.next());                      
             
             System.out.println(mpf.getOriginalFilename() +" uploaded! "+files.size());
 
             //2.2 if files > 10 remove the first from the list
             if(files.size() >= 10)
                 files.pop();
 
             //2.3 create new Image            
             
             try {               
                image = imageService.saveTmpImage(mpf,width);
                files.add(image);
             } catch (IOException e) {
                e.printStackTrace();
                errorMsj = e.getMessage();
             } catch (UserException e) {
            	 System.err.println(e.getMessage());
            	 errorMsj = e.getMessage();
             }
              
              
         }
        // result will be like this
        // [{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]
        				 
 		 //init Gson
 		 Gson gson = new Gson();
 		 String json;
 		 if(files.size()>0){
 			    json = gson.toJson(files);
 		        json = json.substring(0, json.length()-2);
 		        json = json +",\"websiteId\":\""+websiteId+"\",\"finalWidth\":\""+width+"\",\"finalHeight\":\""+height+"\"}]";
 		 }else{
 			 json = "[{\"error\":\""+errorMsj+"\"}]";
 		 }
 		 return json;
        
    }
    
    /***************************************************
     * URL: controller/get/{value}
     * get(): get file as an attachment
     * @param response : passed by the server
     * @param value : value from the URL
     * @return void
     ****************************************************/
    @RequestMapping(value = "/crop", method = RequestMethod.POST)
     public @ResponseBody String cropImage(@RequestParam("cropData") String jsonString){
    	Image image = null;
    	String jsonResponse = "{\"error\":\"null data\"}";
    	String key ="";
    	String pageId="";
    	JsonArray json = Utils.getJsonArray(jsonString);
		key = json.get(0).getAsJsonObject().get("key").getAsString();
		pageId = Utils.getJsonVar(json,"pageId");
				  		
        if(files.size()>0){
    		
    		 Map<String, Integer> mp = Utils.getImageDimension(key,pageId,website,myProps);
    		 int width = (Integer) mp.get("width");
			 int height = (Integer) mp.get("height");
    		 if(key.equals("design") || key.equals("header") || key.equals("header_gal") || key.equals("dataType") || key.equals("archive")){
    			 jsonResponse = imageService.saveImage(json,files.get(0),width,height,key);
    		 }else{
    			 jsonResponse = imageService.saveGalleryImage(json,files.get(0),width,height,key);  
    		 }
    		 
    	 }
        
    	 files.clear();
		return jsonResponse;
     }
    
    @RequestMapping(value = "/deleteGalleryImage", method = RequestMethod.POST)
    public @ResponseBody String deleteImage(@RequestParam("image_id") String id){
    	
    return imageService.daleteGalleryImage(id);
    }
    
    @RequestMapping(value = "/updateGalleryImage", method = RequestMethod.POST)
    public @ResponseBody String updateImage(@RequestParam("Data") String jsonString){
    	Image image = null;
    	JsonArray json = Utils.getJsonArray(jsonString);
    	image = imageService.updateImage(json);
    	
    		return "{\"update\":\"data\",\"id\":\""+image.getId()+"\",\"title\":\""+image.getTitle()+"\",\"caption\":\""+image.getCaption()+"\",\"url\":\""+image.getUrl()+"\"}";
    	
    	}
    
    @RequestMapping(value = "/updateGalleryImagePosition", method = RequestMethod.POST)
    public @ResponseBody String updateImagePosition(@RequestParam("Data") String jsonString){
    	JsonArray json = Utils.getJsonArray(jsonString);
    	imageService.updateImagePosition(json);
    	return "success";
    }
    	
    
    
}
